package cn.e3.order.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.e3.cart.service.AddCartToRedis;
import cn.e3.pojo.TbItem;
import cn.e3.pojo.TbUser;
import cn.e3.sso.service.TokenService;
import cn.e3.utils.CookieUtils;
import cn.e3.utils.E3Result;
import cn.e3.utils.JsonUtils;

public class LoginInterceptor implements HandlerInterceptor{
	@Autowired
	private TokenService tokenService;
	@Autowired
	private AddCartToRedis addCartToRedis;
	@Value("${LOGIN_URL}")
	private String LOGIN_URL;
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		//执行hanlder之前的处理
		//从cookie中取出token
		String token = CookieUtils.getCookieValue(request, "token");
		//判断token是否存在
		if(StringUtils.isBlank(token)){
			//token不存在，返回登录页面,并将请求的路径携带
			response.sendRedirect(LOGIN_URL+"?redirect="+request.getRequestURI());
			//不放行
			return false;
		}
		//token存在，在redis中取用户信息
		E3Result result = tokenService.getUserByToken(token);
		//判断用户信息是否过期
		if(result.getStatus()!=200){
			//token不存在，返回登录页面,并将请求的路径携带
			response.sendRedirect(LOGIN_URL+"?redirect="+request.getRequestURI());
			//不放行
			return false;
		}
		//得到用户信息
		TbUser user = (TbUser) result.getData();
		//将用户信息存入域中
		request.setAttribute("user", user);
		//判断cookie中是否存在购物项信息
		String json = CookieUtils.getCookieValue(request, "cart", true);
		if(StringUtils.isNotBlank(json)){
			//购物项合并到redis中
			addCartToRedis.merge(user.getId(),JsonUtils.jsonToList(json, TbItem.class));
		}
		//放行
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}
	
}
